/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dcm4che;

import DBConnections.MySQL_Query;
import DBConnections.ServerData;
import GUI.JFrameBase;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import libraries.PathLibrary;
import libraries.SystemCall;
import org.dcm4che2.tool.dcmgpwl.DcmGPWL;
//import org.dcm4che2.tool.dcmmwl.DcmMWL;
import org.dcm4che2.tool.dcmups.DcmUPS;

/**
 *
 * @author aeguzkiza
 */

public class dcmUWPS {
    public static class MyException extends Exception { // TESTING THIS POSSIBILITY.
        static final int FileError = 1;
        static final int SystemCallError = 2;
        private int type;
        private String string;

        public MyException(int type, String string) {
            super();
            this.type = type;
            this.string = string;
        }

        @Override
        public String getMessage() {
            switch (type) {
            case FileError:
                    return "No se ha encontrado el archivo correspondiente a la adquisición seleccionada en la ruta:\n["+string+" ]";
            case SystemCallError:
                    return "Es posible que la configuración del servidor no sea correcta, \npara resolver el problema revise la ventana de configuración.\n\nHa surgido un fallo de comunicación con el PACS al realizar la siguiente llamada cmd:\n["+string+" ]";
            default:
                    return "Error desconocido: string = "+string+" type = "+type;
            }
        }
    }

    // Loading libraries
    MySQL_Query DB = new MySQL_Query();
    SystemCall SC = new SystemCall();
    PathLibrary PL = new PathLibrary();
    //LibreriaLanguage LL = new LibreriaLanguage();
    ServerData SD = new ServerData(1);
    //DcmMWL dcmmwl = new DcmMWL("dcmmwl");       // Modality Worklist.
    //DcmGPWL dcmgpwl = new DcmGPWL("dcmgpwl");   // General Purpose Worklist.
    //DcmUPS dcmups = new DcmUPS("dcmups create DCM4CHEE@localhost:11112 -f \"C:/Documents and Settings/aeguzkiza/Escritorio/Test images/dcmups/ncreate.xml\" ");       // Unifyed Procedure Step.
    //DcmUPS dcmups = new DcmUPS("dcmups");       // Unifyed Procedure Step.

    // Global variables
    private String pathLibrary = PL.getdcm4chePath();   // Get's the path where library is located.;

    private String options = "";

    private String dcm4che = null;
    private String cmd = null;
    private String buffer = null;
    private boolean isError = false;
    private String error = "";
    private ArrayList worklist = new ArrayList();

    public dcmUWPS(JFrameBase frame) throws MyException, SQLException{     // Follows all the sending process.
        System.out.println("pathLibrary: "+this.pathLibrary);
        options = "-mod=OPV -aet=AITOR -date="+frame.parseDate(null);   // Requests the worklist by the AETitle of the device, by the modality selected,and today's date. .
        String operation = "create";
        // DCM4CHE2 VIA COMMAND LINE:
        String pathDcmups = pathLibrary+"\\dcmups";
        //this.dcm4che = "\""+pathDcmmwl+"\" "+operation+" "+SD.getServerAETitle()+"@"+SD.getServerHost()+":"+SD.getServerPort()+" "+options;
        //WORKS ON CMD! Similar to dcmRCV! this.dcm4che = "\""+pathDcmups+"\" -LUPSWATCH@localhost:11113";
        //LITTLE ERROR! I think is due to the desconexion between host and server. First run host listener. Second, run server but relate host by -AET.
        
        // Schedule new UPS from XML file:
        //this.dcm4che = "\""+pathDcmups+"\" create DCM4CHEE@LDISENOEI02:11112 -aet AITOR -device AITOR -f \"C:\\Documents and Settings\\aeguzkiza\\Escritorio\\Test images\\dcmups\\ncreate.xml\" -upspush";

        // Subscribe UPS watcher:
        //this.dcm4che = "\""+pathDcmups+"\" subscribe DCM4CHEE@LDISENOEI02:11112 -aet AITOR -iuid 1.2.40.0.13.1.1.130.206.163.14.20110411203832695.32772 -dellock";

        // Change UPS status to IN PROGRESS:
        //this.dcm4che = "\""+pathDcmups+"\" chstate DCM4CHEE@LDISENOEI02:11112 -state=\"IN PROGRESS\" -iuid=1.2.40.0.13.1.1.130.206.163.14.20110411203832695.32772 -tuid=1.2.40.0.13.1.1.130.206.163.14.20110411203832695.32772.1";

        // Change UPS status to CANCELLED:
        //this.dcm4che = "\""+pathDcmups+"\" chstate DCM4CHEE@LDISENOEI02:11112 -state=\"CANCELLED\" -iuid=1.2.40.0.13.1.1.130.206.163.14.20110411203832695.32772 -tuid=1.2.40.0.13.1.1.130.206.163.14.20110411203832695.32772.1";

        // Retrieve canceled UPS:
        this.dcm4che = "\""+pathDcmups+"\" get DCM4CHEE@LDISENOEI02:11112 -iuid=1.2.40.0.13.1.1.130.206.163.14.20110411203832695.32772";


        this.cmd = "cd \""+pathLibrary+"\" && "+dcm4che+"\n";
        /*this.cmd = "cd \""+pathLibrary+"\"";
        for(int i=0;i<this.dcm4che.size();i++){
            this.cmd += " && "+dcm4che.get(i)+"\n";
        }*/

        this.buffer = null;
        try{
            //String inPath="C:\\Documents and Settings\\aeguzkiza\\Escritorio\\Test images\\dcmups\\ncreate.xml";
            //File xml = new File(inPath);
            //dcmups.load(xml);

            /*dcmups.setCalledAET(SD.getServerAETitle());
            dcmups.setRemoteHost(SD.getServerHost());
            dcmups.setRemotePort(Integer.parseInt(SD.getServerPort()));
            
            dcmups.create();
            System.out.println("Hola moe");*/

            //List<DicomObject> workList =
            //System.out.println("WorkList list: "+workList);

            // Setting parameters before doing the query.
            /*
            dcmups.setCalledAET(SD.getServerAETitle());
            dcmups.setRemoteHost(SD.getServerHost());
            dcmups.setRemotePort(Integer.parseInt(SD.getServerPort()));
            
            dcmups.setCalledAET("DCM4CHEE");
            dcmups.setRemoteHost("130.206.163.14");
            dcmups.setRemotePort(11112);
            

            dcmups.query(); // Run a query toget the Worklist from the PACS.*/
            
            Object result[] = SC.SystemCall(cmd);
            this.isError = Boolean.valueOf(result[0].toString());         // Cast Object to boolean.
            this.error = "Error en los parámetros de configuración de captura de la Worklist";
            this.buffer = (String) result[1];
            System.out.println("ERROR RESULT: "+error);

        }catch(Exception ex){
            Logger.getLogger(JFrameBase.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.println("cmd: "+cmd);
        System.out.println("buffer: "+buffer+"\n");

        if(isError == true){    // Error check.
            String CmdSliced = "cd \""+pathLibrary+"\"\n && "+dcm4che;    // The cmd call have been sliced to show it on an alert window.
            throw new MyException(MyException.SystemCallError, CmdSliced );
        }


        // Update worklist and Study tables using captured information.
        /*String[] var0 = new String[]{"1"};  // Write send=1 on database for the corresponding acquisition.
        DB.SQLupdate("UPDATE acquisition SET Sent=? WHERE AcquisitionName='"+acquisition+"'",false,var0.length,var0);
        DB.closeConnection();*/

    }
    public ArrayList getWorklist(){ // Array co0ntaining scheduled study list.
        return this.worklist;
    }
    public String getDcm4che(){
        return this.dcm4che;
    }
    public String getCMD(){
        return this.cmd;
    }
    public String getBuffer(){
        return this.buffer;
    }
    public String getError(){
        return this.error;
    }
}
